import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  Tree,
  message,
  Badge,
  Divider,
  InputNumber,
  Radio,
} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';
import {ruleP, nameMaxLength,remarkMaxLength} from '@/utils/rule'
const FormItem = Form.Item;
const InputGroup = Input.Group;
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;

const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const CreateForm = Form.create()(props => {
  const { modalVisible, form, addDataFn, updateFn, handleModalVisible, text, orgTreeData, setUsercode, userCode } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.info("text2:" + text);
      console.info("userCode:" + userCode);
      if(!text && !userCode){
        Modal.warning({title:'请选择组织树'});
        return;
      }
      console.info("text3:" + text);
      console.info("userCode:" + userCode);
      if(text && !userCode){
        Modal.warning({title:'请选择组织树'});
        return;
      }
      if(text) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };

  const onSelect = (info,e) => {
    const userCode = e.node.props.id;
    setUsercode(userCode)

  }

  const loop = data => data.map((item) => {
    if (item.children) {
      return (
        <TreeNode key={item.id} title={item.orgName} {...item}>
          {loop(item.children||[])}
        </TreeNode>
      );
    }
    return <TreeNode key={item.id} title={item.orgName} {...item}/>;
  });

  const defaultId = text&&text.userCode+ '';

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑空间配置':'新增空间配置'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <div style={{maxHeight: 500,overflowX: 'hidden'}}>
      <Form>
        <Row gutter={16}>
          <Col md={24}>
            <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="空间分配">
              {form.getFieldDecorator('totalSize', {
                rules: [{ required: true,message:'空间分配不能为空'}], initialValue: text&&text.totalSize || ''
              })(
                <InputNumber min={0} max={2097152} step={10} placeholder="最大2T" style={{width:'300px'}} />)
              }&nbsp;&nbsp;M/人
            </FormItem>
          </Col>

          <Col md={24} style={{display: text == null ? 'none' : 'block',}}>
            <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="状态">
              {form.getFieldDecorator('status', {initialValue: text&&text.status
              })(<Radio.Group>
                <Radio value={0}>
                  启用
                </Radio>
                <Radio value={1}>
                  禁用
                </Radio>
              </Radio.Group>)}
            </FormItem>
          </Col>

          {!text?<Col md={24}>
            <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="组织结构">
              <DirectoryTree
                multiple
                onSelect={onSelect}
                defaultExpandedKeys={[defaultId]}
                defaultSelectedKeys={[defaultId]}
              >
                {
                  orgTreeData && orgTreeData.length && loop(orgTreeData||[])
                }
              </DirectoryTree>
            </FormItem>
          </Col>:null}
        </Row>
      </Form>
      </div>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({ organization, loading }) => ({
  organization,
  loading: loading.models.organization,
}))


@Form.create()
class organization extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    text: {},
    orgTreeData: [],
    userCode: '',
  };

  columns = [
    {
      title: '组织名称',
      dataIndex: 'name',
    },
    {
      title: '上级组织',
      dataIndex: 'parentName',

    },
    {
      title: '空间（M/人）',
      dataIndex: 'totalSize',

    },
    {
      title: '状态',
      dataIndex:'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true,text)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDeleteData(text.id)}>删除</a>
          {/*<Popconfirm title="是否要删除此行？" onConfirm={() => this.handleDeleteData(text)}>
            <a>删除</a>
          </Popconfirm>*/}
        </Fragment>
      ),
    },
  ];

  handleDeleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(id),
    });
  };

  setUsercode = (v) => {
    this.setState({
      userCode: v,
    })
  }

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.handleDeleteData(ids); //批量删除
  };

  // 删除方法
  deleteItem(id) {
    const { dispatch } = this.props;
    dispatch({
      type: 'organization/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
          this.setState({selectedRows: []})
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      name: data&&data.name,
      minSize: data&&data.minSize,
      maxSize: data&&data.maxSize,
      userType: 2,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'organization/queryList',
      payload: values,
    });
  }

  componentDidMount() {
    this.pageList();
    this.orgUserTree();//组织树请求
  }

  orgUserTree() {
    const { dispatch } = this.props;
    dispatch({
      type: 'organization/orgTree',
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            orgTreeData: res.data.dataList,
          })
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

   handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;   
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);
    });
  };
// 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
      userCode: text&&text.userCode?text.userCode:''
    });
  };

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    // const { userCode } = this.state;
    const params = {
      userType: 2,
      totalSize:fields.totalSize,
      status:fields.status,
      id: text.id,
      // userCode: userCode?userCode:text.userCode,
    }
    dispatch({
      type: 'organization/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const { userCode } = this.state;
    const params = {
        userType: 2,
        totalSize:fields.totalSize,
        userCode
    }
    dispatch({
      type: 'organization/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={6} sm={24}>
            <FormItem label="组织名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="空间范围">
              <InputGroup>
                {getFieldDecorator('minSize')(
                  <InputNumber min={0} max={2097152} step={10} placeholder="0-2097152" style={{width: 150}}  />
                )}
                <span>&nbsp;~&nbsp;</span>
                {getFieldDecorator('maxSize')(
                  <InputNumber min={0} max={2097152} step={10} placeholder="0-2097152" style={{ width: 150}} />
                )}
            </InputGroup>
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
  const {formValues} = this.state;
  // 分页请求
  this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  render() {
    const {
      organization: { data },
      loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, stepFormValues, text, orgTreeData, userCode } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      setUsercode: this.setUsercode,
    };

    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text} orgTreeData={orgTreeData} userCode={userCode}/>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
      </Card>
    );
  }
}

export default organization;
